package com.ihemou.gateway.filter;

import cn.dev33.satoken.id.SaIdUtil;
import com.ihemou.common.core.constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author saperliu
 * @version 1.0.0
 * @date 2021-08-30 11:46
 * @Description 内部服务权限校验，在请求处增加id-token
 */
@Component
public class ForwardAuthFilter implements GlobalFilter {

    private static final Logger log = LoggerFactory.getLogger(ForwardAuthFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 设置用户信息到请求
        String idToken = SaIdUtil.getToken();
        log.info("gateway id-token: {} {} {} {} {}",idToken, exchange.getRequest().getRemoteAddress(), exchange.getRequest().getURI().getPath(), exchange.getRequest().getQueryParams(),exchange.getRequest().getHeaders());

        ServerHttpRequest newRequest = exchange
                .getRequest()
                .mutate()
                // 为请求追加 Id-Token 参数
                .header(SaIdUtil.ID_TOKEN, idToken)
                .build();

        // 内部请求来源参数清除
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        removeHeader(mutate, Constants.SERVICE_REQUEST);

        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);
    }
    private void removeHeader(ServerHttpRequest.Builder mutate, String name)
    {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }
}
